import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/modle/play/entity/after_pay_entity.dart';
import 'package:shopping_group/modle/play/ui/zfb_html_page.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class FugouRuningPlayBloc implements BlocBase {
  //定时器
  Timer _timer;
  //设定时间
  int seconds = 0;
  //时间格式
  String _content = '00:59:59';

  // Stream来处理计数器
  StreamController<String> _counterController = StreamController<String>();
  StreamSink<String> get _inAdd => _counterController.sink;
  Stream<String> get sendDate => _counterController.stream;

  //  Stream来处理计数器上的操作
  StreamController<String> _actionController = StreamController<String>();
  //接收传值的对象
  StreamSink get incrementDate => _actionController.sink;

  StreamController<String> _timeController = StreamController<String>();
  //接收传值的对象
  StreamSink get timerDate => _timeController.sink;
  //  Stream来初始化数量的操作
  StreamController<Object> _playController = StreamController<Object>();
  //初始化动作
  StreamSink get playDate => _playController.sink;

  StreamController<Object> _zfbPlayController = StreamController<Object>();
  StreamSink get zfbPlayDate => _zfbPlayController.sink;

  StreamController<Object> _zfbPlayCompeteController =
      StreamController<Object>();
  StreamSink get zfbPlayCompeteDate => _zfbPlayCompeteController.sink;
  FugouRuningPlayBloc() {
    _timeController.stream.listen(timeData);
    _playController.stream.listen(playData);
    _zfbPlayController.stream.listen(zfbPlayData);
    _zfbPlayCompeteController.stream.listen(zfbPlayCompeteData);
  }

  void zfbPlayData(data) {
    if (data is Map) {
      // FlutterAlipay.isInstalled().then((value) {
      //   if (null != value && value is bool && value) {
      //
      //   }
      // });
      _zfbPlayTask(data);
    }
  }

  void zfbPlayCompeteData(data) {
    if (data is Map) {
      _zfbPlayCompeteTask(data);
    }
  }

  void timeData(data) {
    if (data is String) {
      _countDown(_content);
    }
  }

  _countDown(count) {
    _content = count;
    seconds = 3600; //1小时
    startTimer();
  }

  void startTimer() {
    //设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //更新界面
      //秒数减一，因为一秒回调一次
      seconds--;
      _content = constructTime(seconds);
      _inAdd.add(_content);
      if (seconds == 0) {
        //倒计时秒数为0，取消定时器
        cancelTimer();
      }
    });
  }

  //时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式
  String constructTime(int seconds) {
    int hour = seconds ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    return formatTime(hour) +
        ":" +
        formatTime(minute) +
        ":" +
        formatTime(second);
  }

  //数字格式化，将 0~9 的时间转换为 00~09
  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  void playData(data) {
    if (data is Map) {
      _playTask(data);
    }
  }

  void _zfbPlayCompeteTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());

    //BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.ZFB_PLAY_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          eventBus.fire(ZfbCompeteEvent());
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _zfbPlayTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());

    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.TESTZFB_PLAY_URL, data: data, headers: {},
            success: (result) {
          if (null != result) {
            SvEntity svEntity = SvEntity.fromJson(result);
            String openType;
            switch (data['type']) {
              case BaseConstant.SHOP_TYPE:
                openType = 'ESOT_SHOP';
                break;
              case BaseConstant.PINGTUAN_TYPE:
                openType = 'ESOT_JOIN';
                break;
              case BaseConstant.XIANJINGJUAN_TYPE:
                openType = 'ESOT_MO';
                break;
              case BaseConstant.FUGOUJUAN_TYPE:
                openType = 'ESOT_RB';
                break;
              default:
            }

            RouteUtil.goParameter(ZfbHtmlPage(
              htmlData: svEntity.val.split(',')[1],
              openType: openType,
              orderId: data['id'],
              orderName: data['orderName'],
            ));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _playTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());

    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.COMMO_PLAY_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            AfterPayEntity parm = AfterPayEntity.fromJson(result);
            if ('PO_ZI_FU_BAO' == data['payOption'] ||
                'Y' == data['isUserZfb']) {
              parm.name = '订单：${parm.id}';
              parm.price = data['price'];
              eventBus.fire(ZfbStartEvent(parm));
            } else {
              BotToast.showText(text: '支付成功');
              if (data['openType'] == 'order') {
                eventBus.fire(RefreshOrderEvent(data['orderId']));
                RouteUtil.closeView();
              } else if (data['openType'] == 'fuGood') {
                RouteUtil.popUntil(PageConstance.MAIN_PAGE);
                RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
              } else if ('dfk' == data['openType']) {
                RouteUtil.popUntil(PageConstance.DFK_VIEW_PAGE);
              } else {
                RouteUtil.popUntil(PageConstance.MAIN_PAGE);
                RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
              }
            }
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    cancelTimer();
    _actionController?.close();
    _counterController?.close();
    _timeController?.close();
    _playController?.close();
    _zfbPlayController?.close();
    _zfbPlayCompeteController?.close();
  }
}
